package cn.gzmli.dtt.common.controll;

import cn.gzmli.dtt.common.entity.Codeinfo;
import cn.gzmli.dtt.common.entity.PageInfo;
import cn.gzmli.dtt.common.entity.Result;
import cn.gzmli.dtt.common.service.CodeInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * @Author: yangxiong
 * @Date: 2018/7/13 16:15
 * @Description:
 * @Modified
 */
@RestController
@RequestMapping("codeInfo")
public class CodeInfoController {
    private static final String CODEMARK_NAME = "codeMarkName";//标识名称
    private static final String CODEINFO_NAME = "codeInfoName";//编码名称
    private static final String DUPLICATE_ENTRY="Duplicate entry";//重复条目
    @Autowired
    CodeInfoService codeInfoService;

    @RequestMapping("list")
    public Result list(Codeinfo codeinfo, PageInfo pageInfo) throws Exception {
        List list = codeInfoService.list(codeinfo, pageInfo);
        return new Result(1, "list", list, pageInfo);
    }

    @RequestMapping("save")
    public Result save(@Valid Codeinfo codeinfo) {
        codeinfo.setCreateTime(new Date());
        int r = 0;
        try {
            r = codeInfoService.save(codeinfo);
        } catch (Exception e) {
            if (e.getMessage().contains(CODEMARK_NAME)&&e.getMessage().contains(DUPLICATE_ENTRY)){
                return new Result(-1,"标识名称已存在");
            }else if(e.getMessage().contains(CODEINFO_NAME)&&e.getMessage().contains(DUPLICATE_ENTRY)){
                return new Result(-1, "编码名称已存在");
            }
            e.printStackTrace();
        }
        return new Result((int) r, r > 0 ? "成功" : "失败");
    }

    @RequestMapping("update")
    public Result update(@Valid Codeinfo codeinfo) {
	    int r = 0;
        try {
         r = codeInfoService.update(codeinfo);
        } catch (Exception e) {
            if (e.getMessage().contains(CODEMARK_NAME)&&e.getMessage().contains(DUPLICATE_ENTRY)){
                return new Result(-1,"标识名称已存在");
            }else if(e.getMessage().contains(CODEINFO_NAME)&&e.getMessage().contains(DUPLICATE_ENTRY)){
                return new Result(-1, "编码名称已存在");
            }
            e.printStackTrace();
        }
        return new Result((int)r, r > 0 ? "成功" : "失败");
    }

    @RequestMapping("delete")
    public Result delete(Codeinfo codeinfo){
        int r = codeInfoService.delete(codeinfo);
        return new Result(r, r > 0 ? "成功" : "失败");
    }

}
